<template>
	<view class="page-main">
		<view class="form-box">
			<u--form ref="uForm" :model="rewrdForm" :rules="rules" labelPosition="left" labelWidth="auto">
				<u-form-item label="奖励内容" prop="rewrdContent" borderBottom>
					<u--input v-model="rewrdForm.rewrdContent" placeholder="请填写" border="none" inputAlign="right" />
				</u-form-item>
				<u-form-item label="亲密值" prop="integral" borderBottom>
					<u--input type="number" v-model="rewrdForm.integral" placeholder="请填写" maxlength="9"
						border="none" inputAlign="right" />
				</u-form-item>
				<u-form-item label="可兑换次数(0=不限)" prop="convertibleTimes" borderBottom>
					<view style="display: flex;justify-content: flex-end;">
						<u-number-box v-model="rewrdForm.convertibleTimes" :min="0" :max="99" integer color="#fff"
							bgColor="#2979ff !important" iconStyle="color: #fff;" />
					</view>
				</u-form-item>
				<u-form-item label="奖励图片" labelPosition="top">
					<u-upload ref="uploadFile" accept="media" :fileList="imageValue" multiple :maxCount="3"
						:maxSize="maxFileSzie" @afterRead="onAfterReadFile" @oversize="onOversizeFile"
						@delete="onDeleteFile" />
				</u-form-item>
			</u--form>
		</view>


		<view style="margin-top: 80rpx;">
			<u-button type="success" text="提交" @click="onSubmit()" />
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isEdit: false,
				rewrdForm: {
					rewrdContent: null,
					images: null,
					integral: null,
					convertibleTimes: 1
				},
				imageValue: [],
				maxFileSzie: 1024 * 1024 * 10, // 最大文件10M
				rules: {
					rewrdContent: [{
						type: 'string',
						required: true,
						message: '请输入奖励内容',
						trigger: ['blur', 'change']
					}],
					integral: [{
						type: 'number',
						required: true,
						message: '请输入所需亲密值',
						trigger: ['blur', 'change']
					}]
				}
			}
		},
		onLoad(option) {
			if (option.id) {
				this.isEdit = true;
				const db = uniCloud.database()
				db.collection('reward')
					.doc(option.id).get({
						getOne: true
					}).then((res) => {
						this.rewrdForm = res.result.data
						if (this.rewrdForm.images) {
							this.imageValue = [{
								url: this.rewrdForm.images
							}]
						}
					}).catch((err) => {
						console.log(err);
					})
			}
		},
		methods: {
			onAfterReadFile(event) {
				let fileList = [].concat(event.file)
				fileList.map(item => {
					this.imageValue.push({
						url: item.thumb,
						fileUrl: item.url,
						status: 'upload'
					})
				})
			},
			onOversizeFile() {
				uni.$u.toast('文件大小不能超过10M');
			},
			onDeleteFile(event) {
				this.imageValue.splice(event.index, 1)
			},
			onSubmit() {
				if (this.$tools.getUser().state == 0) {
					uni.$u.toast('请先绑定伴侣');
					return;
				}

				this.$refs.uForm.validate().then(res => {
					uni.showLoading({
						title: '操作中',
						mask: true
					});
					if (this.imageValue && this.imageValue.length > 0) {
						this.$refs.file.upload();
					} else {
						this.uploadSuccess();
					}

				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
			uploadSuccess(e) {
				let pages = getCurrentPages(),
					prevPage = pages[pages.length - 2],
					rewrdForm = this.rewrdForm,
					oldImages = rewrdForm.images

				rewrdForm.images = this.imageValue && this.imageValue.length > 0 ? this.imageValue[0].url : null
				rewrdForm.integral *= 1
				rewrdForm.convertibleTimes = rewrdForm.convertibleTimes == 0 ? -1 : rewrdForm.convertibleTimes * 1

				const db = uniCloud.database()
				if (this.isEdit) {
					if (oldImages) {
						uniCloud.callFunction({
							name: 'deleteFile',
							data: {
								fileList: [oldImages]
							}
						})
					}

					let rewrdId = rewrdForm._id
					delete rewrdForm._id
					db.collection('reward')
						.doc(rewrdId)
						.update(rewrdForm).then((res) => {
							rewrdForm._id = rewrdId
							uni.hideLoading();
							uni.$u.toast('下发成功');

							uni.navigateBack({
								success: () => {
									let list = prevPage.$vm.list
									let index = list.findIndex(item => item._id === rewrdId)
									list.splice(index, 1, rewrdForm)
									// if (prevPage.data.curNow == 1) {
									// 	prevPage.onLoad()
									// }
								}
							});
						}).catch((err) => {
							uni.hideLoading();
						})

					return;
				}
				const user = this.$tools.getUser()
				rewrdForm.userId = user._id
				rewrdForm.redeemerId = user.partnerId
				db.collection('reward')
					.add(rewrdForm)
					.then((res) => {
						rewrdForm._id = res.result.id
						uni.hideLoading();
						uni.$u.toast('下发成功');

						uni.navigateBack({
							success: () => {
								prevPage.$vm.list.unshift(rewrdForm)
							}
						});
					}).catch((err) => {
						uni.hideLoading();
					})
			},
			//上传失败
			uploadFail(e) {
				uni.hideLoading();
				uni.$u.toast('上传失败')
			},
		}
	}
</script>

<style lang="scss" scoped>
	.form-box {
		padding: 20rpx 30rpx;
		border-radius: 20rpx;
		background-color: rgba(255, 255, 255, 0.85);
	}

	::v-deep .u-upload__button.data-v-69e2a36e {
		margin: 10px 0 0;
	}

	::v-deep .u-upload__wrap__preview.data-v-69e2a36e {
		margin: 10px 8px 0 0;
	}

	::v-deep .u-upload__deletable.data-v-69e2a36e {
		height: 16px;
		width: 16px;
	}

	::v-deep .u-upload__deletable__icon.data-v-69e2a36e {
		transform: scale(0.9);
		-webkit-transform: scale(0.9);
		top: 2px;
		right: 2px;
	}
</style>